/**
 * 查询科目数据
 * **/
define(['apps/utils/tools','apps/utils/chart'],function (tools,chart){
	
  	  var domId = "content",dimCode="kemu",dimArr,defaultChartSwf = "Column3D";
  	  
	  /** 
	   * 初始方法
	   */
	  function init (){
	  	  //视图切换
	  	  //tools.viewChange();
	  	  //绑定事件
	  	  bindEvent();
	  };
	  
	  function getDimParams(dimArr){
    	var bean={};
    	for(var i=0,len=dimArr.length;i<len;i++){
    	    bean[dimArr[i]] = $("#"+dimArr[i]).val();
    	}
    	return bean;
    };
	  
	 /**
     * 执行查询事件
     */
     function exeuteQuery(bean){
     	 var params = getDimParams(dimArr);
         params["period"] = getPeriod(params);
         delete params.month;
         delete params.year;
         for(var key in params){
            params[key] = params[key].join(",");
         }
         tools.applyIf(params,Utils.bean);//把所有obj变量的所有属性都 给bean变量
         params.level = (params.level-0)+1;
		tools.console(params);
		var url = tools.getBasePathUrl() + params.spcode+"/kemudatas.cnbi";
		//var url = tools.getBasePathUrl() + params.spcode+"/kemu_new_datas.cnbi";
		tools.mask('dataContent');
        tools.ajax({url : url,dataType : 'html',data :params,success:success});
     }
     
     function success(msg){
		$("#dataContent").empty().append(msg);	
		
		  var $measure = $('.measure');
      	  var seriesname = [];
      	  $measure.each(function(){
      	  	 seriesname.push($(this).attr('title'));
      	  });
      	  if(seriesname.length == 0){
      	  	var $peroid = $('.period');
      	  	$peroid.each(function(){
      	  	 seriesname.push($(this).attr('title'));
      	  	});
      	  }
      	  var swf = "MSColumn3D";
      	  var bean = getMutiChartDatas(swf,seriesname);
      	  if(bean.dataset.length == 0)
      	  	return;
      	  chart.createMultiSeriesChart(bean);
      	  tools.unmask('dataContent');
      	  chartGroup(seriesname);
	 }
		
	  var chartDatas = null;
	  
	  function getMutiChartDatas(swf,seriesname){
	  	var $obj = $("#kemuTbody").children();
	  	var category = [];
	  	$obj.each(function(index,o){
	  		var $temp = $(o).children().eq(0);
	  		category.push({label:$temp.attr("title")});
	  	});
      	   var caption,data = [],obj = {};
           $obj.each(function(index,o){
              var $temp = $(o).children();
               $temp.each(function(index,bean){
               	   var title = $(bean).attr("title");
               	   if(title != undefined){
               	   		var measure = $(bean).attr("measure");
               	   		for (var i = 0; i < seriesname.length; i++) {
               	   			if(title == seriesname[i]){
               	   				if(measure != undefined)
               	   					data.push({title:title,value:measure});
               	   			}
               	   		}
               	   }
               });
          });
          var dataset = [],datas = [];
          for (var k = 0; k < seriesname.length; k++) {
	          for (var j = 0; j < data.length; j++) {
	          	 if(seriesname[k] == data[j].title){
	          	 	datas.push({value:data[j].value});
	          	 }
	          }
	          obj["seriesname"] = seriesname[k];
	          obj["data"] = datas;
	          dataset.push(obj);
	          obj = {},datas=[];
          }
         // caption = "动态展示图";
    	  chartDatas = {category:category,dataset:dataset,domId:'chartId',swf:swf,height:300};
          return  chartDatas;
	  };
     
	  //绑定事件
	  function bindEvent(){
	  		//列表组 点击事件
	  	  listgroupEvent();
	  	  //单击表格一行
	  	  tableSingleClick();
	  	  //所有 checkbox 选择
	  	  allSelected();
	  	  //一级科目 checkbox
	  	  oneSelected();
		  //全不选
	  	  clearSelect();
	  	  //确定按钮
	  	  sureClick();
	  };
	  
	   function chartGroup(seriesname){
          $("#kemuChartGroup>li >a").bind("click",function(){
               chart.createMultiSeriesChart(getMutiChartDatas($(this).attr("id"),seriesname));
          });
      }
	  //维度选择 至多只允许 两个维度多选
	  function composeChoice(dim){
	  	  dimArr = tools.getDimArrByMap(Utils.dimMapJson);
		  dimComponentClick(dimArr);
	  };
  
	  /**
	   * 排除indicator维度下的组件 绑定事件
	   */
	  function bindExpInDim(dimArr){
			for(var i=0,len=dimArr.length;i<len;i++){
				if(dimArr[i] != "company" && dimArr[i] !='measure' && dimArr[i] !='kemu'){
				   var css = "applyCls";
				   $("dd[name="+dimArr[i]+"]>a").addClass("applyCls");
				}
			   $("#"+dimArr[i]).attr('multiple','multiple');//multiple="multiple"
			}
	  }
	  
	  function dimComponentClick(dimArr){
	  		bindExpInDim(dimArr);
     		dimAEventBind(dimArr);
			dimSelectEventBind(dimArr);
	  };
	   /**
     * select 事件绑定
     */
	function dimSelectEventBind(dimArr){
    	for(var i=0,len=dimArr.length;i<len-1;i++){
    	    componentEventSelectbind(dimArr[i],dimArr);
    	}
    }
    function componentEventSelectbind(dim,dimArr){
    	  $("#"+dim).unbind();  
    	 // tools.console("给Select--"+dim+"绑定了事件--->");
    	  $("#"+dim).bind("change",function(){
    	  	  dim = $(this).attr("id");
    	  	  var val = $(this).val();
    	  	   styleChangeA({dim:dim,dom:null});
    	       exeuteQuery({dim:dim,owner:$(this).text()});
    	  });
    	
     }
	   /**
      * 获取期间维度组合
      */
     function getPeriod(params){
     	var dim={singleSelect:true};
     	var showDim = [];
     	for(var key in params){
              var len = params[key].length;
              if(len > 1){
                  dim["name"] = key;
                  showDim.push(dim["name"]);
                  dim["singleSelect"] = false;;
              }
         }
         params["showDim"] = showDim;
         var period = [];
         var yearLen = params["year"].length,monthLen =  params["month"].length;
	              for(var i=0;i<yearLen;i++){
	                  for(var j=0;j<monthLen;j++){
	                   period.push(params["year"][i]+params["month"][j]);
	                 }
	              }
     	return period;
     }
     
	   /**
     * A组件事件
     * param obj Dom对象
     */
    function dimAEventBind(dimArr){
    	for(var i=0,len=dimArr.length;i<len;i++){
    	   componentEventAbind(dimArr[i],dimArr);
    	}
    }
    
    function componentEventAbind(dim,dimArr){
    	 //tools.console("给A--"+dim+"绑定了事件--->");
         $("dd[name="+dim+"] >a").unbind(); 
         $("dd[name="+dim+"] >a").click(function(){
	        var  dim = $(this).parent().attr("name"),scode = $(this).attr("scode"),
	        $obs = $('#'+dim+' option[value="'+scode+'"]');
	          var xx =  styleChangeA({dim:dim,dom:this});
	          if(dim == "company") showCompany(dim,$(this));
 	          if(xx.flag == "add"){
	             $obs.attr('selected',true); 
	          }else if(xx.flag == "remove"){
	              $obs.attr('selected',false); 
	          }else if(xx.flag == "single"){
	            $("#"+xx.dim).val(scode);
	          }
	         exeuteQuery({dim:dim,owner:$(this).text()});
	     });
    }
    
    function showCompany(dim,$dom){
     	$dom.addClass(tools.cls);
    }
    
    function getNum(dim){
    	var x = 0;
    	$("dd[name="+dim+"] > a").each(function(){//单击自身是否选中多个
    		if($(this).hasClass(tools.cls)){
    			 if(dim == "company"){//现在为单体公司
    			 	if(!$(this).hasClass("btn-default")){$(this).addClass("btn-default");}
    			 	$(this).removeClass(tools.cls);
    			 	$('#company').children().each(function(){
			    		if($(this).attr('selected') == 'selected'){
			    			$(this).removeAttr('selected');
			    		}
    				});
    			 }
    		     x++;
    		}
    	});
    	return x;
    }
	  /**
     * 当a选择时
     */
    function styleChangeA(obj){
    	var dim = obj["dim"],msgBean = {},singleSelect = {msg:'',flag:true};//regCls = "btn btn-primary applyCls";
    	for(var i=0,count=0,len=dimArr.length;i<len;i++){
    		 var aDim = dimArr[i],dimLen = 0,sel={};
    		 $("dd[name="+aDim+"] >a").each(function(index,o){
    		     if($(this).hasClass(tools.cls)){
    		       dimLen++;
    		       sel = o;
    		     }
    		 });
    		
    		var msg = '',flag=true;
    		if(dimLen > 1 ){
    			count++;
    		}
    		var num = 2;
    		if(getNum('month') > 1 && getNum('year') > 1){
    			if(dim=='kemu'||dim=='measure')
    				num = 3;
    		}
			if(count == num){
    		 	if(dimLen > 1 ){
	    		    flag = false;
	    		    var dimName = $("dd[name="+aDim+"] >a").parent().prev().text();
	    		    msg = "维度【"+dimName+"】已经多选了！";
	    		    singleSelect["msg"]= dimName;
	    		    singleSelect["dim"]= aDim;//
	    		   	singleSelect["flag"]= false;
	    		    singleSelect["size"]= dimLen;
    		    }
    		 }
    		 msgBean[aDim] = {sel:sel,dim:aDim,flag:flag,msg:msg,size:dimLen};
    	}
    	var x = getNum(dim);
    	if(x > 1){
    		singleSelect["dim"]= dim;
    		if(singleSelect["flag"]) singleSelect["flag"]= false;
    	}
    	//tools.console(msgBean);
    	if(null != obj["dom"]){//A过来的
	    	var $o = $(obj["dom"]);
	    	if(!singleSelect["flag"]){//如果不是单选：即多选
	    		 if(singleSelect["dim"] == dim){//如果多选的维度等于点击的维度
	    		   //if(singleSelect["size"]>1){//即：至少保留一个是选中的
	    		       if(!$o.hasClass(tools.cls)){
	    		           $o.addClass(tools.cls);
	    		           return {flag:"add"};
	    		       }else{
	    		           tools.removeSelect(obj["dom"]);
	    		           return {flag:"remove"};
	    		       }
	    		   //}else return {flag:"add"};
	    		}else{//remove:msgBean[dim]["sel"]
	    			tools.styleChange(obj["dom"]);
	    			return {dim:dim,flag:"single"};//
	    		}
	    	}else{////如果单选
	    	   tools.setSelect(obj["dom"]);
	    	   return {flag:"add"};
	    	}
    	}else{//select过来的
    	      var valArr = $("#"+dim).val(),len = valArr.length;
    	      if(!singleSelect["flag"] && len>1){//如果不是单选：即多选
    	      	    tools.alertMsg("select过来的两个多选的 !有时候再加吧！");
    	      }else{
    	           for(var y=0;y<len;y++){
    	             $("dd[name="+dim+"] >a").each(function(index,o){
    	             	if($(o).attr("scode") == valArr[y]){
    	             	     tools.setSelect(o);
    	             	}else{
    	             	    tools.removeSelect(o);
    	             	}
    		         });
    	      		}
    	      }
    	}}
  
	  //一级科目选择
	  function oneSelected(){
	  	 $('#oneSelect').click(function(){
	  	 	$('input[type=checkbox]').each(function(){
	  	 		if($(this)[0].attributes.nlevel.value == 1){
				  	checkboxCheckedTbody($(this));
	  	 		}
	  	 	});
	  	 });
	  };
	  
	  //点击确定按钮事件
	  function sureClick(){
		  $('#sure').click(function(){
		  	 //获取选中 科目
		  	 var obj = getKemu();
		  	 if(obj.length == 0){
		  	 	return;
		  	 }
		  	 //导航条设置title
		  	 var sname = setlevelNav(obj);
		  	 //隐藏科目列表的div
		  	 tools.otherDimShow();
		  	 //导航条
		  	 tools.levelNav({scode:obj[0]["scode"],sname:"所选科目【"+sname+"】",level:3});
	         tools.navEventBind();
	         //科目维度选择
	         createKemuSelected(obj);
	         //维度选择事件
	  	  	 composeChoice(Utils.dimMapJson);
		  });
	  };
	  
	  function setMesssureOne(){
	  	var len = 0;
	  	 $("dd[name=measure] >a").each(function(){
    		  if($(this).hasClass(tools.cls)){
    		       len++;
    		  }
    		  if(len > 1) tools.removeSelect($(this));
    	});
    	$('#measure').children().each(function(){
    		if($(this).attr('selected') == 'selected'){
    			$(this).removeAttr('selected');
    		}
    	});
	  }
	  //选择的 科目维度显示
	  function createKemuSelected(dimArr){
	  	//单点击 面包屑导航条重新选择 可能会出现 多维度选择情况 默认再将  messsure 设置为  单选择
	  	if(dimArr.length > 1)
	  		setMesssureOne();//单度量
	  	var datas ='',selectData='',sname="";// '<dl class="dl-horizontal"> <dt>指标</dt><dd class="box" name="indicator">';
        for (var i = 0; i < dimArr.length; i++) {
        	var n = dimArr[i]["sname"],c=dimArr[i]["scode"],cls = "btn btn-primary ";
        	if(i != 0){
        		cls+=dimCode;
        	}
        	 datas+='<a title="'+n+'" href="javascript:;" class="'+cls+'" scode="'+c+'">'+n+'</a>';
             selectData+='<option value="'+c+'">'+n+'</option>';
             if(i<8){
                sname+=n+"&nbsp;";
             }
        }
	    $("dd[name="+dimCode+"]").empty().append(datas);
     	$("#"+dimCode).empty().append(selectData).attr('multiple','multiple');//multiple="multiple"
     	$("#"+dimCode+" option").attr("selected","selected");
     	
        return datas;
	  };
	  
	  //设置导航条
	  function setlevelNav(arr){
	  	//num 设置 选中科目的最多的个数
	  	 var str = '',num = 5,len = arr.length;
	  	 if(len > num){
	  	 	str = getStr(str,num,arr);
	  	 	str = str + '  ...';
	  	 }else{
	  	 	str = getStr(str,len,arr);
	  	 }
	  	 return str;
	  };
	  
	  function getStr(str,len,arr){
	  	 for (var i = 0; i < len; i++) {
  	 		var obj = arr[i];
  	 		str = str + obj.sname;
  	 		if(i != len - 1){
  	 			str = str + '、';
  	 		}
	  	 }
	  	 return str;
	  };
	  
	  //获取选中科目
	  function getKemu(){
	  	 var userArr = [];
  		 //所有选中 checkbox
  		 $('table input[type=checkbox][checked]').each(function(){
  		 	 var thisObj = $(this)[0].attributes;
  		 	 var bean = {};
  		 	 bean.scode = thisObj.scode.value;
  		 	 bean.sname = thisObj.sname.value;
  			 userArr.push(bean);
  		 });
  		 return userArr;
	  };
	  
	  //全不选
	  function clearSelect(){
	  	//全不选
	  	 $('#clearSelect').click(function(){
	  	 	 unchecked();
	  	 });
	  };
	  
	  function unchecked(){
  		$('input[type=checkbox]').each(function(){
			  if(this.checked){
			  	this.checked = false;
			  	$(this).removeAttr('checked');
			  }
		 });
	  };
	   //全选与反选
	  function allSelected(){
	  	 $('#allSelect').click(function(){
	  	 	$('input[type=checkbox]').each(function(){
				  if(this.checked){
				  	
				  }else{ 
				  	this.checked = true;
				  	$(this).attr('checked','checked');
				  }
			 });
	  	 });
	  };
	  
	   //单击表格一行
	  function tableSingleClick(){
	  		 //表格 
		  $('tbody >tr').bind('click',function(){
		  	  tools.applyTableSingleSelectClickStyle(this);
		  	  var $checked = $(this).children().children().eq(1);//'input[type=checkbox]'
		  	  checkboxCheckedTbody($checked);
		  	   //一级科目添加级联选择
	  	  	  oneSelectCascade($checked,$(this));
		  });
	  };
	  
	  //一级科目级联选择
	  /**
	   * @param $checked 一级科目 input jquery
	   * @param $this 父亲 tr
	   * */
	  function oneSelectCascade($checked,$this){
	  	 var scode = $checked[0].attributes.scode.value;
  	 	 $this.nextAll().each(function(){
  	 		var $sel = $(this).children().children().eq(1);
  	 		var spcode = $sel[0].attributes.spcode.value;
  	 		if(scode == spcode){
  	 			checkboxCheckedTbody($sel);
  	 			//回调执行级联选择
  	 			oneSelectCascade($sel,$(this));
  	 		}
  	 	 });
	  };
	  
	  //$check jquery 对象
	  function checkboxCheckedTbody($check){
	  	if($check[0].checked){
  		 	 $check.removeAttr('checked');
		  }else{ 
		  	$check.attr('checked','checked');
		 }
	  };
	  
	  //列表组点击事件
	  function listgroupEvent(){
	  	$('.list-group').children().each(function(){
	  		$(this).click(function(){
	  			$('.list-group').children().each(function(){
	  				if($(this).hasClass('active'))$(this).removeClass('active');
	  			});
	  			$(this).addClass('active');
	  		});
	  	});
	  };
	  
	  return {
	    init : init
	  }
});